package com.example.elderlycare.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.elderlycare.controller.entity.BerthRequestBody;
import com.example.elderlycare.dao.entity.Berth;
import com.example.elderlycare.dao.entity.NursingHome;
import com.example.elderlycare.service.BerthService;
import com.example.elderlycare.service.NursingHomeService;
import com.example.elderlycare.service.entity.BerthListResponseBody;
import com.example.elderlycare.utils.Result;
import com.example.elderlycare.utils.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/berth")
public class BerthController {

    @Resource
    BerthService berthService;

    @Resource
    NursingHomeService nursingHomeService;

    /**
     * 查询床位信息
     *
     * @param nursingHome 养老院名称
     * @param number      床位编号
     * @param free        是否空闲，1--空闲，0--不空闲
     * @param pageSize    页大小
     * @param current     当前页
     * @return BerthListResponseBody
     */
    @GetMapping
    public Result<BerthListResponseBody> queryBerths(
            @RequestParam(value = "nursingHome", required = false) String nursingHome,
            @RequestParam(value = "number", required = false) String number,
            @RequestParam(value = "free", required = false) Integer free,
            @RequestParam(defaultValue = "10", value = "pageSize") int pageSize,
            @RequestParam(defaultValue = "1", value = "current") int current
    ) {
        Map<String, Object> params = new HashMap<>(5);
        params.put("nursingHome", nursingHome != null ? "%" + nursingHome + "%" : null);
        params.put("number", number != null ? "%" + number + "%" : null);
        params.put("free", free);
        params.put("limit", pageSize);
        params.put("offset", (current - 1) * pageSize);
        try {
            BerthListResponseBody res = berthService.queryBerths(params);
            return Result.success(res);
        } catch (Exception e) {
            log.warn("Exception", e);
            return Result.error(ResultEnum.DEFAULT_ERROR);
        }
    }

    /**
     * 批量生成插入养老院床位信息
     *
     * @param req BerthRequestBody.addBerth
     * @return null
     */
    @PostMapping
    public Result<?> addBerths(@Valid @RequestBody BerthRequestBody.AddBerth req) {
        NursingHome nursingHome = nursingHomeService.getById(req.getNursingHomeId());
        /* 查出当前养老院最大房间号码 */
        QueryWrapper<Berth> berthQueryWrapper = new QueryWrapper<>();
        berthQueryWrapper.eq("nursing_home_id", req.getNursingHomeId())
                .orderByDesc("id")
                .last("limit 1");
        Berth maxBerth = berthService.getOne(berthQueryWrapper);
        int lastNumber = 0;
        /* 当前养老院存在床位 */
        if (maxBerth != null) {
            String maxNumber = berthService.getOne(berthQueryWrapper).getNumber();
            maxNumber = maxNumber.substring(maxNumber.length() - 4);
            /* 获取当前养老院最后一个房间的号码 */
            lastNumber = Integer.parseInt(maxNumber);
        }
        List<Berth> berths = new ArrayList<>(req.getTotal());
        for (int i = 0; i < req.getTotal(); i++) {
            Berth berth = Berth.builder()
                    .nursingHomeId(req.getNursingHomeId())
                    .number(nursingHome.getCode() + String.format("%04d", lastNumber + i + 1))
                    .build();
            berths.add(berth);
        }
        try {
            boolean success = berthService.saveBatch(berths);
            if (success) {
                return Result.success(null);
            } else {
                log.warn("add Berths error");
                return Result.error(ResultEnum.DEFAULT_ERROR);
            }
        } catch (Exception e) {
            log.warn("Exception", e);
            return Result.error(ResultEnum.DEFAULT_ERROR);
        }
    }

    /**
     * 删除床位信息
     *
     * @param ids 记录id集合
     * @return null
     */
    @DeleteMapping
    public Result<?> deleteBerth(@RequestParam(value = "ids") String[] ids) {
        try {
            boolean success = berthService.removeByIds(Arrays.stream(ids).collect(Collectors.toList()));
            if (success) {
                return Result.success(null);
            } else {
                log.warn("delete Berth error");
                return Result.error(ResultEnum.DEFAULT_ERROR);
            }
        } catch (Exception e) {
            log.warn("Exception", e);
            return Result.error(ResultEnum.DEFAULT_ERROR);
        }
    }
}
